import React, {Component} from 'react';
import {connect} from "react-redux";
import {HomeWrap, HomeLeft, HomeRight, BackToTop} from './style';
import * as actionCreators from '../../actions/HomeAction';

import List from './components/List';
import Recommend from './components/Recommend';
import Topic from './components/Topic';
import Writer from './components/Writer';

import bannerImg from '../../statics/imgs/banner.jpg'

class Home extends Component {

    handleScrollToTop() {
        window.scrollTo({
            top: 0,
            left: 0,
            behavior: "smooth"
        })
    }

    scrollEvents() {
        const {changeBackToTopShow} = this.props;
        window.addEventListener('scroll', changeBackToTopShow);
    }

    render() {
        const {showBackToTop} = this.props;
        return (
            <HomeWrap>
                <HomeRight>
                    <Recommend />
                    <Writer />
                </HomeRight>
                <HomeLeft>
                    <img className="banner" src={bannerImg} alt="banner-img" />
                    <Topic />
                    <List />
                </HomeLeft>
                {
                    showBackToTop ? (<BackToTop onClick={this.handleScrollToTop}>
                                        <i className="iconfont icontop"></i>
                                    </BackToTop>) : null
                }

            </HomeWrap>
        )
    }

    componentDidMount() {
        const {getRecommendList, getTopicList, getArticleList} = this.props;
        getRecommendList();
        getTopicList();
        getArticleList();
        this.scrollEvents();
    }
}

const mapStateToProps = (state) => {
    return {
        showBackToTop: state.getIn(['home', 'showBackToTop'])
    }
};

const mapDispatchToProps = (dispatch) => {
    return {
        getRecommendList() {
            dispatch(actionCreators.getRecommendList())
        },
        getTopicList() {
            dispatch(actionCreators.getTopicList());
        },
        getArticleList() {
            dispatch(actionCreators.getArticleList())
        },
        changeBackToTopShow() {
            if(document.documentElement.scrollTop > 400){
                dispatch(actionCreators.changeBackToTopShow(true));
            } else {
                dispatch(actionCreators.changeBackToTopShow(false));
            }
        }
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);